<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <div>
                <el-button type="primary" :icon="Plus" size="default" @click="addTradeMark">添加</el-button>
            </div>
        </template>
        <!-- card body -->
        <el-table :data="tableData" border :style="{ marginBottom: '20px' }" stripe>
            <el-table-column align="center" label="序号" type="index" width="80" />
            <el-table-column prop="tmName" label="品牌名称" />
            <el-table-column prop="logoUrl" label="品牌LOGO">
                <!-- 通过插槽的形式，接收传递过来的参数，就是tableData -->
                <template #default="{ row }">
                    <img height="60" :src="row.logoUrl" alt="">
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="warning" size="small" :icon="Edit" @click="UpdateTradeMark(row)">修改</el-button>
                    <el-button type="danger" size="small" :icon="Delete" @click="deleteTrademark(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination 
        v-model:page-size="limit" 
        v-model:current-page="page" 
        :pager-count="5" small background
        :page-sizes="[5, 9, 12, 15]" 
        layout="prev, pager, next,sizes" 
        :total="total" 
        class="mt-4" />
    </el-card>

    <!-- 弹窗的信息可以写在外面 -->
    <el-dialog v-model="dialogFormVisible" :title="newTradeMark.id ? '修改品牌' : '添加品牌'">
        <el-form 
        label-width="100px"
        ref="ruleFormRef"
        :model="newTradeMark"
        :rules="rules"
        >
            <el-form-item label="品牌名称" prop="tmName">
                <el-input autocomplete="off" v-model='newTradeMark.tmName' />
            </el-form-item>
            <el-form-item label="品牌LOGO" prop="logoUrl">
                <el-upload class="avatar-uploader" :action="`${baseUrl}/admin/product/upload`" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="newTradeMark.logoUrl" :src="newTradeMark.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">退出</el-button>
                <el-button type="primary" @click="updateOrAddTrademark">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from "vue";


export default defineComponent({
    name: "TradeMark",
});
</script>

<script setup lang="ts">
import { ref, toRefs, onMounted, watch, reactive } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
//引入请求api
import { requestTradePageList, 
    type TradeRecordsItemType,
     type TradeRecordsType, 
     requestUpdateTrademark, 
     requestAddTrademark,
     requestDeleteTrademark
    } from '@/api/tradeMark';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import type { UploadProps } from 'element-plus'

//模板数据
const tableData = ref<TradeRecordsType>([])

//1、页码逻辑
//定义页码可以直接const每个，也可以创建一个对象
//定义页码的类型
interface pageDataType {
    page: number;
    limit: number;
    total: number;
}
//
const pageData = ref<pageDataType>({
    page: 1,
    limit: 5,
    total: 100,
})
//解构出页码数据，转为响应式数据
const { page, limit, total } = toRefs(pageData.value)
//监听页码变化
watch([page, limit], () => {
    //当页码变化时。重新发请求
    getTrademarkList()
})


//2、获取分页列表逻辑
//创建函数发送请求
const getTrademarkList = async () => {
    const re = await requestTradePageList({ page: page.value, limit: limit.value })
    //赋值给数据
    tableData.value = re.records
    //总页数赋值给total
    total.value = re.total
}

onMounted(() => {
    getTrademarkList()
})

//定义的弹窗布尔值
const dialogFormVisible = ref(false)


//3、添加弹窗中的上传逻辑
const imageUrl = ref('')

// 定义一个请求基础路径
const baseUrl = import.meta.env.VITE_API_URL
//收集数据
const newTradeMark = ref<TradeRecordsItemType>({
    tmName: '',
    logoUrl: ''
})

//提交成功时的方法
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    //这里上传就是获取url
    //   imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    //   console.log(imageUrl.value);
    //   console.log(response); //响应体
    newTradeMark.value.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

//4、修改逻辑，因为函数
const UpdateTradeMark = (row: TradeRecordsItemType) => {
    //每次点开清除表单校验
    ruleFormRef.value?.clearValidate()
    //打开弹窗
    dialogFormVisible.value = true;
    //通过插槽拿到当前行自带的数据，无需请求
    // console.log(row,'11');
    // 直接赋值给newTradeMark,通过浅拷贝则不会影响数据
    newTradeMark.value = { ...row }
}


//5、点击添加逻辑
const addTradeMark = () => {
    //每次点开清除表单校验
    ruleFormRef.value?.clearValidate()
    //打开弹窗
    dialogFormVisible.value = true;
    //设置收集值为空
    newTradeMark.value = {
        tmName: '',
        logoUrl: ''
    }
}

//6、新增和修改的提交
// 获取表单实例，来做整体校验
const ruleFormRef = ref<FormInstance>()
const updateOrAddTrademark = async () => {
    try{
        // 整体表单校验
        await ruleFormRef.value?.validate()
        try {
        if (newTradeMark.value.id as number) {
            //如果有id则时修改数据
            await requestUpdateTrademark(newTradeMark.value)
            ElMessage.success("修改成功");
        } else {
            await requestAddTrademark(newTradeMark.value)
            ElMessage.success("新增成功");
        }
    } catch (e) {
        ElMessage.error(newTradeMark.value.id ? "修改错误" : "新增错误")
    }
    //不管如何关闭弹窗
    dialogFormVisible.value = false;
    //重新发送请求
    getTrademarkList();
    }catch(e){

    }
}

//7、删除的逻辑
const deleteTrademark=async(id:number)=>{
    ElMessageBox.confirm(
    '你确定要删除吗？警告！',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
       //获取到id
        // console.log(id,'11');
        // 发送请求
        try{
            await requestDeleteTrademark(id)
            ElMessage.success('删除成功')
             //重新发送请求
            getTrademarkList();
        }catch(e){
            ElMessage.error('删除错误')
        }
    })
    .catch(() => {
      ElMessage.info('点错了吧')
    })
   
   
}

//8、校验表单

//创建表单规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '内容不能有空', trigger: 'blur' },
    { min: 1, max:6, message: '名称长度必须为1-6', trigger: 'blur' },
  ],
  logoUrl: [
    {
      required: true,
      message: '上传图片不能为空',
      trigger: 'change',
    },
  ],
})
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
    <style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>